# 让球胜平负

# 每天抽取让球赔率最低的两场比赛

from loaddata.mgDB import JinCaiDatabase,Wan500Database
import datetime
import pandas as pd
# 获取让1球的比赛
def getDatasByDay(day):
    query = {'matchTime': {'$eq': "2024-02-20"}}
    ds = JinCaiDatabase.get_jincai(query)
    selectds = []
    for dx in ds:
        goalLine = dx.get("goalLine")
        if goalLine == "-1" or goalLine == "+1":
            # 胜平负
            a = dx.get("a")  # 负
            h = dx.get("h")  # 胜
            d = dx.get("d")
            winFlag = dx.get("winFlag").lower()
            matchNo = dx.get("matchNo")
            sectionsNo999 = dx.get("sectionsNo999")

            # 让球胜平负(开奖赔率)
            fixedBonus = dx.get("fixedBonus")
            hhadList = fixedBonus.get("oddsHistory").get("hhadList")
            if hhadList:
                hhad = hhadList[-1]
                ha = float(hhad.get("a"))  # 负
                hh = float(hhad.get("h"))  # 胜
                hd = float(hhad.get("d"))  # 平
            # 让球胜平负（开奖结果）
            matchResultList = fixedBonus.get("matchResultList")
            if len(matchResultList) > 0:
                for m in matchResultList:
                    if m.get("code") == 'HHAD':
                        combination = m.get("combination").lower()
                        selectds.append({"matchNo":matchNo,"sectionsNo999":sectionsNo999,"goalLine":goalLine,"hda":{"h":h,"d":d,"a":a,"w":winFlag},"hhda":{"h":hh,"d":hd,"a":ha,"w":combination}})
    return selectds

# 获取让1球的比赛
def getDatas(start,end):
    query = {'matchTime': {'$gte': start, '$lt': end}}
    ds = JinCaiDatabase.get_jincai(query)
    selectds = []
    for dx in ds:
        goalLine = dx.get("goalLine")
        if dx.get("a"):
            if goalLine == "-1" or goalLine == "+1":
                # 胜平负
                a = float(dx.get("a"))  # 负
                h = float(dx.get("h"))  # 胜
                d = float(dx.get("d"))
                winFlag = dx.get("winFlag").lower()
                matchNo = dx.get("matchNo")
                sectionsNo999 = dx.get("sectionsNo999")
                matchTime = dx.get("matchTime")
                matchNumStr = dx.get("matchNumStr")

                # 让球胜平负(开奖赔率)
                fixedBonus = dx.get("fixedBonus")
                hhadList = fixedBonus.get("oddsHistory").get("hhadList")
                if hhadList:
                    hhad = hhadList[-1]
                    ha = float(hhad.get("a"))  # 负
                    hh = float(hhad.get("h"))  # 胜
                    hd = float(hhad.get("d"))  # 平
                # 让球胜平负（开奖结果）
                matchResultList = fixedBonus.get("matchResultList")
                if len(matchResultList) > 0:
                    for m in matchResultList:
                        if m.get("code") == 'HHAD':
                            combination = m.get("combination").lower()
                            selectds.append({"matchTime": matchTime, "matchNo": matchNo, "sectionsNo999": sectionsNo999,
                                             "matchNumStr":matchNumStr,"goalLine": goalLine, "hda": {"h": h, "d": d, "a": a, "w": winFlag},
                                             "hhda": {"h": hh, "d": hd, "a": ha, "w": combination}})

    sds = []
    for s in selectds:
        sd = {"matchNumStr":s.get("matchNumStr"),"matchTime":s.get("matchTime"),"matchNo":s.get("matchNo"),"sectionsNo999":s.get("sectionsNo999"),"goalLine":s.get("goalLine"),"dp":{},"gp":{}}
        if s.get("goalLine") == "+1":  # 让胜，胜平负取负，让球胜平负取胜（让胜）
            geta = s.get("hda").get("a")  # 胜平负取负
            geth = s.get("hhda").get("h")  # 让球胜平负取胜
            # 判断是否命中
            aw = 0
            hw = 0
            if s.get("hda").get("w") == "a":  # 命中
                aw = 1
            if s.get("hhda").get("w") == "h":  # 命中
                hw = 1
            ga = {"p": geta, "w": aw,"hda":"a","cname":"负"}
            gh = {"p": geth, "w": hw,"hda":"h","cname":"让胜"}

            sd["dp"] = gh  # 如果相等，默认让球为低赔
            sd["gp"] = ga  # 高赔
            # 比较高低
            if geta < geth:
                sd["dp"] = ga
                sd["gp"] = gh

        if s.get("goalLine") == "-1":  # 让负，胜平负取胜，让球胜平负取负（让负）
            geth = s.get("hda").get("h")  # 胜平负取胜
            geta = s.get("hhda").get("a")  # 让球胜平负取负
            # 判断是否命中
            aw = 0
            hw = 0
            if s.get("hda").get("w") == "h":  # 命中
                hw = 1
            if s.get("hhda").get("w") == "a":  # 命中
                aw = 1
            ga = {"p": geta, "w": aw,"hda":"a","cname":"让负"}
            gh = {"p": geth, "w": hw,"hda":"h","cname":"胜"}

            sd["dp"] = ga  # 如果相等，默认让球为低赔
            sd["gp"] = gh  # 高赔
            # 比较高低
            if geth < geta:
                sd["dp"] = gh
                sd["gp"] = ga
        sds.append(sd)


    # 按照时间分组  每天的再按照低赔从低到高的排序，并将每组转换为词典
    df = pd.DataFrame(sds)
    grouped_dicts = df.groupby('matchTime').apply(lambda x: x.to_dict('records')).to_dict()
    paixu = []
    for key in grouped_dicts:
        tt = sorted(grouped_dicts.get(key), key=lambda e: e["dp"]["p"], reverse=False)
        paixu += tt

    # 按照时间排序
    # 根据'age'键进行排序（从小到大）
    sorted_list = sorted(paixu, key=lambda x: x['matchTime'],reverse=True)
    return sorted_list

'''
开始时间
结束时间
'''
def moniter(start,end):
    datestart = datetime.datetime.strptime(start, '%Y-%m-%d')
    dateend = datetime.datetime.strptime(end, '%Y-%m-%d')

    while datestart < dateend:
        # 下载数据兵解析(一天的数据，有很多场比赛)
        datas = getDatasByDay(datestart)
        # print(datas)
        # 继续下个1天
        datestart += datetime.timedelta(days=1)


# if __name__ == '__main__':
    # 最早的竞猜记录时间2014-10-22
    # start = '2024-02-01'
    # end = '2024-02-03'
    # rs = moniter(start,end)

    # 定义一个包含多个字典的列表
    # data = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 25}]

    # 按年龄进行分组
    # grouped_dicts = []
    # for key, group in groupby(sorted(data), lambda x: x['age']):
    #     grouped_dicts.append({'key': key, 'values': list(group)})

    # print(grouped_dicts)

